/*
 * �� �� ��:  ProductListAdapter.java
 * ��    Ȩ:  Weipu Technologies Co., Ltd. Copyright 2012-2014,  All rights reserved
 * ��    ��:  <����>
 * �� �� ��:  sjx206
 * �޸�ʱ��:  2015-1-6
 * ���ٵ���:  <���ٵ���>
 * �޸ĵ���:  <�޸ĵ���>
 * �޸�����:  <�޸�����>
 */
package com.epro.dx.adapter;

import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.webkit.URLUtil;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.epro.dx.R;
import com.epro.dx.activity.DetailActivity;
import com.epro.dx.listenner.OnViewGroupScrollListenner;
import com.epro.dx.pullview.PullToRefreshGridView;
import com.epro.dx.util.ImageLoaderUtils;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.PauseOnScrollListener;
import com.weipu.common.constants.Constant;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.model.ProductModel;
import com.weipu.common.util.Logger;
/**
 * ��Ʒ�б�adapter
 *
 * @author sjx206
 */
public class ProductListAdapter extends CommonAdapter<ProductModel> {

    private RotateAnimation rotate = null;

    private Context context;

    // 是否有HomePublicList页面跳转过来
    private boolean isPubListPage;

    /**
     * 记录是否刚打开程序，用于解决进入程序不滚动屏幕，不会下载图片的问题。
     */
    public boolean isFirstEnter = true;

    private PullToRefreshGridView gridView;

    private OnViewGroupScrollListenner scrollListenner;

    private int densityDpi;

    private  DisplayImageOptions options;

    private String currencyCode = null;//货币简写

    private String currencyCodeSymbol = null;//货币符号

    private Tracker tracker;

    private String recommendRequestId;//推荐产品的回调码
    private boolean needShowMvp;

    public ProductListAdapter(Context context, List<ProductModel> productList,
                              boolean isPLPage,int densityDpi,Tracker tracker) {
        super(productList, context);
        this.context = context;
        this.isPubListPage = isPLPage;
        this.densityDpi=densityDpi;
        rotate = new RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF,
                0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        rotate.setInterpolator(new LinearInterpolator());
        rotate.setDuration(1080);
        rotate.setStartTime(Animation.START_ON_FIRST_FRAME);
        rotate.setRepeatMode(Animation.RESTART);
        rotate.setRepeatCount(Animation.INFINITE);
        options=ImageLoaderUtils.getImageLoaderOptions(R.drawable.item_default,R.drawable.item_default);

    }

    public ProductListAdapter(Context context, List<ProductModel> productList,
                              boolean isPLPage,PullToRefreshGridView gridView,final OnViewGroupScrollListenner scrollListenner,int densityDpi,Tracker tracker) {
        super(productList, context);
        this.context = context;
        this.isPubListPage = isPLPage;
        this.gridView=gridView;
        this.scrollListenner=scrollListenner;
        this.densityDpi=densityDpi;
        rotate = new RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF,
                0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        rotate.setInterpolator(new LinearInterpolator());
        rotate.setDuration(1080);
        rotate.setStartTime(Animation.START_ON_FIRST_FRAME);
        rotate.setRepeatMode(Animation.RESTART);
        rotate.setRepeatCount(Animation.INFINITE);
//		gridView.setOnScrollListener(this);
        gridView.setOnScrollListener(new PauseOnScrollListener(ImageLoader.getInstance(), true, true){
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {
                if(null!=scrollListenner){
                    scrollListenner.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
                }
                super.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
            }

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if(null!=scrollListenner){
                    scrollListenner.onScrollStateChanged(view, scrollState);
                }
                super.onScrollStateChanged(view, scrollState);
            }
        });
        options=ImageLoaderUtils.getImageLoaderOptions(R.drawable.item_default,R.drawable.item_default);
    }

    @Override
    public View getView(final int position, View convertView,
                        final List<ProductModel> list, final Context context) {
        final ViewHolder viewHolder;
        if (null == convertView) {
            convertView = LayoutInflater.from(context).inflate(
                    R.layout.item_product_list, null);
            viewHolder = new ViewHolder();
            viewHolder.prodcutPrice = (TextView) convertView
                    .findViewById(R.id.product_price);
            viewHolder.productIcon = (ImageView) convertView
                    .findViewById(R.id.product_icon);
            viewHolder.productOldPrice = (TextView) convertView
                    .findViewById(R.id.product_old_price);
            viewHolder.productName = (TextView) convertView
                    .findViewById(R.id.product_name);
            viewHolder.ratingBar = (RatingBar) convertView
                    .findViewById(R.id.ratingBar);
            viewHolder.reviewCount = (TextView) convertView
                    .findViewById(R.id.review_count);
            viewHolder.llDiscount = (LinearLayout) convertView
                    .findViewById(R.id.ll_discount);
            viewHolder.tvDiscount = (TextView) convertView
                    .findViewById(R.id.tv_discount);
            viewHolder.llOldPrice = (RelativeLayout) convertView
                    .findViewById(R.id.ll_old_price);
            viewHolder.soldOutImg = (ImageView) convertView
                    .findViewById(R.id.item_product_list_soldout);
            viewHolder.MVPImg = (ImageView) convertView
                    .findViewById(R.id.item_product_list_mvp);
            viewHolder.USImg = (ImageView) convertView
                    .findViewById(R.id.item_product_list_us);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        // ��ȡ��ǰ��ʾ�б�����Ʒ
        if(null==list||position>=list.size()){
            return convertView;
        }
        final ProductModel product =(ProductModel) getItem(position);
        // ������ƷͼƬ����ҳ��ͼƬԪ����ֵ
        if (null != product) {
            double listPrice=product.getListprice();
            double price=product.getPrice();
            if ((listPrice - price) > 0) {
                viewHolder.llDiscount.setVisibility(View.VISIBLE);
                double discountPrice=((listPrice - price) / listPrice)*100;
                int discount=(int)discountPrice;
                double disDecimal=discountPrice-discount;
                //主站逻辑 余数大于0.5时进一位
                if(disDecimal>0.5){
                    viewHolder.tvDiscount.setText(discount+1 + "");
                }else{
                    viewHolder.tvDiscount.setText(discount + "");
                }
//				double discount = (int) (((product.getListprice() - product
//						.getPrice()) / product.getListprice()) * 100);
//				viewHolder.tvDiscount.setText(discount + "");
            } else {
                viewHolder.llDiscount.setVisibility(View.GONE);
            }

//			String[] productIconUrl = product.getSmallPictureURL();
//			String[] productIconUrl=getImageUrl(densityDpi,product,203,300);
            String[] productIconUrl=product.getMediumPictureURL();
            if (null != productIconUrl
                    && productIconUrl.length >= 1
                    && (URLUtil.isHttpUrl(productIconUrl[0]) || URLUtil
                    .isHttpsUrl(productIconUrl[0]))) {
                viewHolder.productIcon.setTag(productIconUrl[0]);
                ImageLoader.getInstance().displayImage(productIconUrl[0], viewHolder.productIcon, options);
            } else {
                viewHolder.productIcon.setImageBitmap(getDefault243(context));
            }

            //viewHolder.productIcon.setTag(product);
            // ��Ʒ���
            viewHolder.productName.setText(product.getShortHeadLine1());
            // ��Ʒ�۸�
            String showCurrency = null;
            if(!TextUtils.isEmpty(currencyCodeSymbol)){
                showCurrency = currencyCodeSymbol;
            }else{
                showCurrency = currencyCode;
            }
//			viewHolder.prodcutPrice.setText(context.getString(
//					R.string.product_price, String.format("%.2f",product.getPrice())));
            viewHolder.prodcutPrice.setText(showCurrency+String.format("%.2f",product.getPrice()));
            // ��Ʒ�˷�
            if (product.getPrice() < product.getListprice()) {
//				viewHolder.productOldPrice.setText(context.getString(
//						R.string.product_price, String.format("%.2f",product.getListprice())));
                viewHolder.productOldPrice.setText(showCurrency+String.format("%.2f",product.getListprice()));
            } else {
                viewHolder.llOldPrice.setVisibility(View.INVISIBLE);
            }
            int reviewCount = product.getReviewCount();
            // ��Ʒ����
            if (reviewCount > 1) {
                viewHolder.reviewCount.setVisibility(View.VISIBLE);
                viewHolder.reviewCount
                        .setText("( " + reviewCount + " reviews)");
            } else if (reviewCount == 1) {
                viewHolder.reviewCount.setVisibility(View.VISIBLE);
                viewHolder.reviewCount.setText("( " + reviewCount + " review)");
            } else {
                viewHolder.reviewCount.setVisibility(View.INVISIBLE);
            }
            viewHolder.ratingBar.setRating((float) product.getProductRating());
            if (!isPubListPage) {
                convertView.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {

                        if (list.size() > position) {
                            if(null!=tracker){
                                tracker.send(new HitBuilders.EventBuilder("Click product","Go to product detail(sku:"+product.getSku()+")").build());
                            }
                            if(!TextUtils.isEmpty(recommendRequestId)){
                                //反馈百分点推荐结果
//								BfdAgent.onFeedback(context, recommendRequestId, product.getSku()+"");
                            }
                            detailIntent(list.get(position));

                        }
                    }
                });
            }

            //APP4.0修改：当状态为2－－预售、3-－暂时停售时显示soldout标签
            if(product.getStatus() == 2 || product.getStatus() == 3){
                viewHolder.soldOutImg.setVisibility(View.VISIBLE);
                viewHolder.llDiscount.setVisibility(View.GONE);
                viewHolder.MVPImg.setVisibility(View.GONE);
                viewHolder.USImg.setVisibility(View.GONE);
            } else {
                //APP4.0修改：MVP标签显示
                int tag = product.getTag();
                if (tag == 1) {
                    viewHolder.MVPImg.setVisibility(View.VISIBLE);
                    needShowMvp = true;
                } else {
                    viewHolder.MVPImg.setVisibility(View.GONE);
                    needShowMvp = false;
                }
                viewHolder.soldOutImg.setVisibility(View.GONE);

                /**
                 * 优先级顺序
                 * Soldout > US仓 > 预售 > MVP
                 */
                //获取sku所在仓库，如果其中有US，则签
                int warehouses = product.getWarehouses();
                if (warehouses == ProductModel.WarehouseTag.US) {
                    //代表是US仓
                    viewHolder.USImg.setVisibility(View.VISIBLE);
                    viewHolder.MVPImg.setVisibility(View.GONE);
                } else {
                    viewHolder.USImg.setVisibility(View.GONE);
                    if (needShowMvp) {
                        viewHolder.MVPImg.setVisibility(View.VISIBLE);
                    }else {
                        viewHolder.MVPImg.setVisibility(View.GONE);
                    }
                }
            }
        }
        return convertView;
    }

    static class ViewHolder {
        TextView productName;

        TextView prodcutPrice;

        TextView productOldPrice;

        TextView reviewCount;

        TextView tvDiscount;

        ImageView productIcon;

        // ImageView productRating;

        // ImageView imgSoldoutIcon;

        ImageView imgStar1;

        RatingBar ratingBar;

        LinearLayout llDiscount;

        RelativeLayout llOldPrice;

        ImageView soldOutImg;
        ImageView MVPImg;
        ImageView USImg;

    }

    public void setRecommendRequestId(String mRecommendRequestId){
        if(!TextUtils.isEmpty(mRecommendRequestId)){
            this.recommendRequestId = mRecommendRequestId;
        }
    }

    /**
     * 跳转详情页面
     *
     * @param product
     *            产品ID
     */
    protected void detailIntent(ProductModel product) {
        Intent intent = new Intent(context, DetailActivity.class);
        Bundle data = new Bundle();

        data.putInt(ServerConstant.Parameter.PARAMETER_NAME_PRODUCT_ID,
                Integer.valueOf(product.getSku()));
        data.putString(ServerConstant.Parameter.PARAMETER_NAME_BACK_ACTION,
                ServerConstant.ActionConstant.ACTION_GADGET);
        data.putString(ServerConstant.Parameter.PARAMETER_NAME_FROM_ACTIVITY,
                ServerConstant.ActionConstant.ACTION_GADGET);
        intent.putExtras(data);

        context.startActivity(intent);
    }


    @Override
    public void notifyDataSetInvalidated() {
        super.notifyDataSetInvalidated();
        isFirstEnter=true;
    }

    public void setFirstEnter(boolean isFirst){
        isFirstEnter=isFirst;
    }

    public void recleBitmap(){
        try {
            if(null!=defaultBitmap&&!defaultBitmap.isRecycled()){
                defaultBitmap.recycle();
                defaultBitmap=null;
            }
        } catch (RuntimeException e) {
            Logger.i("ProductListAdatper", "recleBitmap RuntimeException productList");
        }


    }

    public void setCurrencyCode(String currencyCode,String currencyCodeSymbol){
        this.currencyCode = currencyCode;
        this.currencyCodeSymbol = currencyCodeSymbol;

    }

}
